package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qk.common.PageResult;
import com.qk.dto.operateLog.OperateLogDTO;
import com.qk.entity.OperateLog;
import com.qk.entity.User;
import com.qk.management.mapper.OperateLogMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.OperateLogService;
import com.qk.vo.operateLog.OperateLogVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class OperateLogServiceImpl extends ServiceImpl<OperateLogMapper, OperateLog> implements OperateLogService {
    @Autowired
    private OperateLogMapper operateLogMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public PageResult<OperateLogVO> getLog(OperateLogDTO operateLogDTO) {
        IPage<OperateLog> pages = new Page<>(operateLogDTO.getPage(), operateLogDTO.getPageSize());
        LambdaQueryWrapper<OperateLog> wrapper = Wrappers.lambdaQuery(OperateLog.class);
        String operateUserName = operateLogDTO.getOperateUserName();
        boolean notEmpty = ObjectUtil.isNotEmpty(operateUserName);
        if (notEmpty){
            wrapper.eq(OperateLog::getOperateUserId, userMapper.selectOne(Wrappers.lambdaQuery(User.class).eq(User::getName, operateUserName)).getId());
        }
        IPage<OperateLog> operateLogIPage = this.baseMapper.selectPage(pages, wrapper);
        List<OperateLogVO> operateLogVOList = new ArrayList<>();
        operateLogIPage.getRecords().forEach(operateLog -> {
            OperateLogVO operateLogVO = BeanUtil.copyProperties(operateLog, OperateLogVO.class);
            operateLogVO.setOperateUserName(userMapper.selectById(operateLog.getOperateUserId()).getName());
            operateLogVOList.add(operateLogVO);
        });

        return PageResult.<OperateLogVO>builder()
                .total((int) operateLogIPage.getTotal())
                .rows(operateLogVOList)
                .build();
    }
}
